package thin4ca


class TableRepository extends Repository {

  var tables = List[Table]()
  
  def create(entity: EntityDef) {
    tables = tables ::: List(new Table(entity.name))
    println("create. tables: " + tables);
  }

  def add(id: String, entity: Entity){
    tables.find( _.name equals entity.typez) match {
      case Some(table) => {
        table.add(id, entity);
      }
      case None => error("Not found " + id)
    }
  }

  def find(tableName: String, id: String) : Map[String, Any] = {
    println("find.tables: " + tables);
    tables.find( _.name equals tableName) match {
      case Some(table) =>  {
        table.find(id)
      }
      case None => error("Table not found: " + tableName)
    }
  }
}

class Table(val name: String) {
  var rows = List[Record]()

  def find(id: String) : Map[String, Any] = {
    println("find - rows " + rows)
    rows.find( _.id equals id) match {
      case Some(row) =>  {
        println("table-find " + row.columns)
        row.columns
      }
      case None => error("Row not found: " + id + " in " + name)
    }
  }
  
  def add(id: String, entity: Entity) {
    rows = rows ::: List(new Record(id, entity.readAttrs));
    println("add - rows " + rows)
  }

  override def toString = "Table<name=" + name + ">"
}

class Record(val id: String, val columns: Map[String, Any]) {
  override def toString = "Record<id=" + id + ", columns=" + columns + ">"
}

